package com.sgzn.sgpay.service.tcp.receive.handler;

import com.sgzn.sgpay.service.tcp.receive.TcpReceiveCallHandlerTemplate;
import com.sgzn.sgpay.service.tcp.receive.modle.TcpReceiveCallRequest;
import com.sgzn.sgpay.service.tcp.receive.modle.response.TcpQueryIncrementBabyResult;
import com.sgzn.sgpay.service.tcp.util.SgTcpUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 查询增量应答（娃娃机） 处理器
 * @author huangsenguang
 * @version Id: TcpQueryIncrementBabyHandler.java, v 0.1 2018/7/30 11:20 huangsenguang Exp $$
 */
@Service
@Slf4j
public class TcpQueryIncrementBabyHandler extends TcpReceiveCallHandlerTemplate<TcpQueryIncrementBabyResult> {
    /**
     * 协议总字符数
     */
    @Getter
    private final int protocolLength = 26;

    @Override
    public TcpQueryIncrementBabyResult callInner(TcpReceiveCallRequest request) {
        String data = request.getData();
        TcpQueryIncrementBabyResult result = new TcpQueryIncrementBabyResult();
        result.setRunState(data.substring(0,2));
        result.setErrorCode(data.substring(2,4));
        result.setCoinIncrement(parse(data,4,6));
        result.setRefundIncrement(parse(data,6,8));
        result.setIncomeIncrement(parse(data,8,10));
        return result;
    }

    private int parse(String data, int beginIndex, int endIndex) {
        return Integer.parseInt(SgTcpUtil.sortTcp(data.substring(beginIndex, endIndex)), 16);
    }

    @Override
    protected int getProtocolLength(TcpReceiveCallRequest request) {
        return this.protocolLength;
    }
}

